package master;


/**
 * @author chenyw
 * @date 2022/8/26 12:29
 * 从根节点到叶子结点的和
 */
public class M129sumNumbers {

    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }

    private int dfs(TreeNode root, int preSum) {
        if (root == null) {
            return 0;
        }
        int sum = preSum * 10 + root.val;
        if (root.left == null && root.right == null) {
            return sum;
        } else {
            return dfs(root.left, sum) + dfs(root.right, sum);
        }
    }

/*    //回溯
    int res = 0;
    public int sumNumbers(TreeNode root) {
        dfs(root, 0);
        return res;
    }

    private void dfs(TreeNode root, int sum) {
        if (root == null) {
            return;
        }

        sum = sum * 10;
        sum = sum + root.val;
        if (root.left == null && root.right == null) {
            res += sum;
            System.out.println(res);
            return;
        }
        System.out.println(sum);
        dfs(root.left, sum);
        dfs(root.right, sum);
        sum /= 10;
    }*/
}
